import * as vscode from 'vscode';
import * as path from 'path';
import * as fs from 'fs';

export class Webview {
  static single: any;

  private webviewPanel: vscode.WebviewPanel | undefined | null;

  private constructor() {

  }

  static getSingle(): Webview {
    if (!this.single) {
      this.single = new Webview();
    }
    return this.single;
  }

  public open(url: string, viewType: string, title: string, icon: string, context: vscode.ExtensionContext) {
    if (this.webviewPanel) {
      this.webviewPanel.title = title;
      this.webviewPanel.reveal();
    } else {
      this.webviewPanel = vscode.window.createWebviewPanel(viewType,
        title,
        vscode.ViewColumn.Active,           // 展示在哪个面板上
        {
          retainContextWhenHidden: true,  // 控制是否保持webview面板的内容（iframe），即使面板不再可见。
          enableScripts: true             // 下面的 html 页可以使用 Scripts
        });
    }

    this.webviewPanel.iconPath = vscode.Uri.file(icon);

    this.webviewPanel.onDidDispose(() => {
      this.webviewPanel = null;
    });

    const html = fs.readFileSync(path.join(context.extensionPath, "./src/template.html")).toString();
    this.webviewPanel.webview.html = html.replace("$url", url);
  }

}